package mylibrary.couchDB;

import org.lightcouch.CouchDbClient;
import org.lightcouch.View;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

import java.util.*;

public class Test {

	public static void main(String[] args) {
		
		Gson gson = new Gson();
		
		CouchDbClient dbClient = new CouchDbClient("couchdb.properties");
		
		
		//create a record
//		Map map = new HashMap();
//		map.put("name", "gaoshuai");
//		map.put("age", 100);
//		dbClient.save(map);						//http request return 201
		
		
		//find record by id
//		JsonObject json = dbClient.find(JsonObject.class, "553cbefddcd0461bb4040a1f7e809708");
//		UserDTO user = gson.fromJson(json, UserDTO.class);
		
		
		
		String baseURI = dbClient.getBaseUri().toString();
		String dbURI = dbClient.getDBUri().toString();
		System.out.println(baseURI);
		System.out.println(dbURI);				//http://127.0.0.1:5984/iproject/
		
		String uri = baseURI + "_stats";
		JsonObject stats = dbClient.findAny(JsonObject.class, uri);
	

		//query by view, uderId as parameter
		//		{
		//   "_id": "_design/card",
		//  "_rev": "3-b2058912a234102494d66342a3d0fdcb",
		//   "language": "javascript",
		//   "views": {
		//       "listCard": {
		//           "map": "function(doc) {\n  \n  if(doc.cardNo && doc.cardUser) {\n     emit(doc.cardUser, [doc.cardNo, doc.cardType, doc.balance, doc.remark]);\n\n   }\n\n  }"
		//      }
		//   }
		//}
		String userId = "c71757b158444e6f9859c8d27efc2068";
		View queryView = dbClient.view("card/listCard").key(userId);
		List queryList = queryView.query(JsonObject.class);
		UserDTO user = new UserDTO();
		List<String> result = new ArrayList<String>();
		if(!queryList.isEmpty()) {
			JsonObject jsonResult = (JsonObject) queryList.get(0);
			JsonArray valueField = (JsonArray)jsonResult.get("value");		//["4929420000897333","2",500,"a card"]
			
			Iterator iterator = valueField.iterator();
			while(iterator.hasNext()) {
				JsonPrimitive field = (JsonPrimitive) iterator.next();
				result.add(field.getAsString());
			}
			user.setCardNo(result.get(0));
			user.setCardType(Integer.valueOf(result.get(1)));
			user.setBalance(Float.valueOf(result.get(2)));
			user.setRemark(result.get(3));
			
		}
		
		
		dbClient.remove("3f52d4d98b3c43c192bdf8b1adac195d", "4-337539da84a38e39e93da6a8987cc49a");
		
		
		
	}
}
